<?php
namespace App\Logics;

use App\Models\ChannelModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\CouponModel;
use App\Models\CouCouponModel;
use App\Models\CategoryModel;
use App\Models\ChannelCateGoodsModel;

//逻辑处理
class CouponLogic extends BaseLogic {


    public function __construct()
    {
        parent::__construct();

    }

    public function index(array $para){
        $page = isset($para['page'])?$para['page']:1;
        $per_page = isset($para['per_page'])?$para['per_page']:20;
        $cou_name = isset($para['cou_name'])?$para['cou_name']:'';
        $cou_id = isset($para['cou_id'])?$para['cou_id']:0;
        $cou_status = isset($para['cou_status'])?$para['cou_status']:-1;
        $is_breaks = isset($para['is_breaks'])?$para['is_breaks']:-1;

        $where = $searchWhere = [];

        if ($cou_id > 0) {
            $where['cou_id'] = $cou_id;
            $searchWhere[] = ['cou_id', $cou_id];
        }
        if ($cou_status!=-1) {
            $where['cou_status'] = $cou_status;
            $searchWhere[] = ['cou_status', $cou_status];
        }
        if ($is_breaks!=-1) {
            $where['is_breaks'] = $is_breaks;
            $searchWhere[] = ['is_breaks', $is_breaks];
        }

        if ($cou_name) {
            $where['cou_name'] = $cou_name;
            $searchWhere[] = ['cou_name', 'like', $cou_name . '%'];
        }
        if ($per_page != 20) {
            $where['per_page'] = $per_page;
        }



        $model = CouponModel::where($searchWhere);
        $data = $model->paginate($per_page, ['*'], 'page', $page);
        $data = ob_to_array($data);
        $data['page_list'] = $this->page($data['last_page'], $data['current_page']);
        $data['up_page'] = ($data['current_page'] - 1) > 0 ? $data['current_page'] - 1 : 1;
        $data['next_page'] = ($data['current_page'] + 1) > $data['last_page'] ? $data['last_page'] : $data['current_page'] + 1;
        $url = url()->current() . '?&';
        foreach ($where as $k => $v) {
            $url .= "$k=$v&";
        }
        $data['page_url'] = trim($url, '&');

        $url=config('sys.img_url').'/';

        if(isset($where['per_page']))unset($where['per_page']);
        $arr=[
            'data'=>$data,
            'where'=>$where,
            'url'=>$url
        ];
        return $arr;
    }

    public  function add(array $para,Request $request){
        $cou_name= isset($para['cou_name'])?$para['cou_name']:'';
        $cou_effect=isset($para['cou_effect'])?$para['cou_effect']:'';
        $cou_describe=isset($para['cou_describe'])?$para['cou_describe']:'';
        $cha_name=isset($para['cha_name'])?$para['cha_name']:'';
        $cou_start_time=isset($para['cou_start_time'])?$para['cou_start_time']:'';
        $cou_end_time=isset($para['cou_end_time'])?$para['cou_end_time']:'';
        $cou_sum_price=isset($para['cou_sum_price'])?$para['cou_sum_price']:0;
        $cou_price=isset($para['cou_price'])?$para['cou_price']:0;
        $goods_id=isset($para['goods_id'])?$para['goods_id']:0;

        $cou_status=isset($para['cou_status'])?$para['cou_status']:0;
        $is_breaks=isset($para['is_breaks'])?$para['is_breaks']:0;
        $cou_every_count=isset($para['cou_every_count'])?$para['cou_every_count']:0;
        $cou_expiration=isset($para['cou_expiration'])?$para['cou_expiration']:'';
        $cou_type=isset($para['cou_type'])?$para['cou_type']:1;


        if(empty($cou_name)) return error('请填写优惠券名称');
        if(empty($cou_effect)) return error('请填写优惠券标题');
        if(empty($cou_describe)) return error('请填写优惠券描述');
        $is_breaks=$is_breaks==1?1:2;

        if(empty($cou_sum_price)) return error('请填写满减');
        if(empty($cou_price)) return error('请填写满减优惠金额');
        $cou_sum_price = (float)str_replace(',','',$cou_sum_price);
        $cou_price = (float)str_replace(',','',$cou_price);
        if($cou_sum_price<=0){
            return error('满减必须大于0');
        }
        if($cou_price<=0){
            return error('满减优惠金额必须大于0');
        }
        if($cou_price>=$cou_sum_price){
            return error('满减必须大于满减优惠金额');
        }

        if(empty($cou_start_time)) return error('请填写活动开始时间');
        if(empty($cou_end_time)) return error('请填写活动结束时间');
        $s_time=strtotime($cou_start_time);
        $e_time=strtotime($cou_end_time);
        if($s_time>= $e_time){
            return error('结束时间必须大于开始时间');
        }
        if($cou_expiration<1){
            return error('有效天数必须大于0');
        }
        $cou_status=$cou_status==1?1:2;
        if(empty($cha_name)) return error('请选择渠道');

        $cha_id=ChannelModel::where('cha_name',$cha_name)->value('cha_id');
        if(empty($cha_id)) return error('该渠道不存在');
        if(!isset($_POST['cate_id'])){
            $cate=[0];
        }else{
            $cate=$_POST['cate_id'];
            if(in_array('all',$cate)){
                $cate=['all'];
            }else{
                $cate=array_map(function($v){
                    return (int)$v;
                },$cate);
                $cate=CategoryModel::where("cha_id",$cha_id)->whereIn('cate_id',$cate)->pluck('cate_id');
                $cate=ob_to_array($cate);
                if(empty($cate)) $cate=[0];
            }
        }
        $goods_id=trim($goods_id,',');
        if($goods_id){
            $goods_id=explode(',',$goods_id);
            $goods_id=array_map(function($v){
                return (int)$v;
            },$goods_id);
            $goods_id=ChannelCateGoodsModel::where('cha_id',$cha_id)->whereIn('goods_id',$goods_id)->pluck('goods_id');
            $goods_id=ob_to_array($goods_id);
            if(empty($goods_id))$goods_id=[0];
        }else{
            $goods_id=[0];
        }

        if($cou_every_count<1){
            $cou_every_count=1;
        }
        $cou_type=$cou_type==0?0:1;

        $data=[
            'cou_name'=>$cou_name,
            'cou_effect'=>$cou_effect,
            'cou_describe'=>$cou_describe,
            'is_breaks'=>$is_breaks,
            'cou_sum_price'=>$cou_sum_price,
            'cou_price'=>$cou_price,
            'cou_start_time'=>$cou_start_time,
            'cou_end_time'=>$cou_end_time,
            'cou_status'=>$cou_status,
            'cou_expiration'=>$cou_expiration,
            'cha_name'=>$cha_name,
            'cate_id'=>join(',',$cate),
            'goods_id'=>join(',',$goods_id),
            'cou_every_count'=>$cou_every_count,
            'cou_type'=>$cou_type,
        ];

        $res=ChannelModel::insert($data);
        if(empty($res))  return error('添加失败');
        return success('添加成功');
    }

    public function edit(array $para){
        $cou_name= isset($para['cou_name'])?$para['cou_name']:'';
        $cou_effect=isset($para['cou_effect'])?$para['cou_effect']:'';
        $cou_describe=isset($para['cou_describe'])?$para['cou_describe']:'';
        $cha_name=isset($para['cha_name'])?$para['cha_name']:'';
        $cou_start_time=isset($para['cou_start_time'])?$para['cou_start_time']:'';
        $cou_end_time=isset($para['cou_end_time'])?$para['cou_end_time']:'';
        $cou_sum_price=isset($para['cou_sum_price'])?$para['cou_sum_price']:0;
        $cou_price=isset($para['cou_price'])?$para['cou_price']:0;
        $goods_id=isset($para['goods_id'])?$para['goods_id']:0;
        $cou_status=isset($para['cou_status'])?$para['cou_status']:0;
        $is_breaks=isset($para['is_breaks'])?$para['is_breaks']:0;
        $cou_every_count=isset($para['cou_every_count'])?$para['cou_every_count']:0;
        $cou_expiration=isset($para['cou_expiration'])?$para['cou_expiration']:'';
        $cou_type=isset($para['cou_type'])?$para['cou_type']:1;
        $cou_id=isset($para['cou_id'])?$para['cou_id']:0;

        if(empty($cou_name)) return error('请填写优惠券名称');
        if(empty($cou_effect)) return error('请填写优惠券标题');
        if(empty($cou_describe)) return error('请填写优惠券描述');

        $is_breaks=$is_breaks==1?1:2;
        if(empty($cou_sum_price)) return error('请填写满减');
        if(empty($cou_price)) return error('请填写满减优惠金额');
        $cou_sum_price = (float)str_replace(',','',$cou_sum_price);
        $cou_price = (float)str_replace(',','',$cou_price);
        if($cou_sum_price<=0){
            return error('满减必须大于0');
        }
        if($cou_price<=0){
            return error('满减优惠金额必须大于0');
        }
        if($cou_price>=$cou_sum_price){
            return error('满减必须大于满减优惠金额');
        }

        if(empty($cou_start_time)) return error('请填写活动开始时间');
        if(empty($cou_end_time)) return error('请填写活动结束时间');
        $s_time=strtotime($cou_start_time);
        $e_time=strtotime($cou_end_time);
        if($s_time>= $e_time){
            return error('结束时间必须大于开始时间');
        }
        if($cou_expiration<1){
            return error('有效天数必须大于0');
        }
        $cou_status=$cou_status==1?1:2;
        if(empty($cha_name)) return error('请选择渠道');
        $cha_id= ChannelModel::where('cha_name',$cha_name)->value('cha_id');
        if(empty($cha_id)) return error('该渠道不存在');
        if(!isset($_POST['cate_id'])){
            $cate=[0];
        }else{
            $cate=$_POST['cate_id'];
            if(in_array('all',$cate)){
                $cate=['all'];
            }else{
                $cate=array_map(function($v){
                    return (int)$v;
                },$cate);
                $cate=CategoryModel::where("cha_id",$cha_id)->whereIn('cate_id',$cate)->pluck('cate_id');
                $cate=ob_to_array($cate);
                if(empty($cate)) $cate=[0];
            }
        }
        $goods_id=trim($goods_id,',');
        if($goods_id){
            $goods_id=explode(',',$goods_id);
            $goods_id=array_map(function($v){
                return (int)$v;
            },$goods_id);
            $goods_id=ChannelCateGoodsModel::where('cha_id',$cha_id)->whereIn('goods_id',$goods_id)->pluck('goods_id');
            $goods_id=ob_to_array($goods_id);
            if(empty($goods_id))$goods_id=[0];
        }else{
            $goods_id=[0];
        }

        if($cou_every_count<1){
            $cou_every_count=1;
        }
        $cou_type=$cou_type==0?0:1;

        $data=[
            'cou_name'=>$cou_name,
            'cou_effect'=>$cou_effect,
            'cou_describe'=>$cou_describe,
            'is_breaks'=>$is_breaks,
            'cou_sum_price'=>$cou_sum_price,
            'cou_price'=>$cou_price,
            'cou_start_time'=>$cou_start_time,
            'cou_end_time'=>$cou_end_time,
            'cou_status'=>$cou_status,
            'cou_expiration'=>$cou_expiration,
            'cha_name'=>$cha_name,
            'cate_id'=>join(',',$cate),
            'goods_id'=>join(',',$goods_id),
            'cou_every_count'=>$cou_every_count,
            'cou_type'=>$cou_type,
        ];

        $res=CouponModel::where('cou_id',$cou_id)->update($data);
        if(empty($res))  return error('编辑失败');
        return success('编辑成功');
    }

    public static function delete(int $cou_id){
        $cou_coupon=CouCouponModel::where('cou_id',$cou_id)->count();
        if($cou_coupon>0){
             return error('该优惠券已经被应用不能删除');
        }

        DB::beginTransaction();
        try{
            $res= CouponModel::where('cou_id',$cou_id)->delete();
            if(empty($res)) throw  new \Exception('删除失败');
            $cou_coupon= CouCouponModel::where('cou_id',$cou_id)->count();
            if($cou_coupon>0){
                throw  new \Exception('删除失败');
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
             return error($e->getMessage());
        }
        return success('删除成功');
    }

    public  function getEdit(int $cou_id){
        $coupon= CouponModel::where('cou_id',$cou_id)->first();
        $coupon=ob_to_array($coupon);
        if(empty($coupon))  return error('参数错误');
        $coupon['cate_id']=explode(',',$coupon['cate_id']);
        $channel= ChannelModel::pluck('cha_describe','cha_name');
        $channel=ob_to_array($channel);
        $cha_id=ChannelModel::where('cha_name',$coupon['cha_name'])->value('cha_id');
        $category= CategoryModel::where('cha_id',$cha_id)->select('cate_id','cate_name','pid')->get();
        $category=ob_to_array($category);
        $category=$this->tree($category);

       return  [
           'channel'=>$channel,
           'coupon'=>$coupon,
           'category'=>$category
       ];
    }

    public static function getCoupon($fields=['*']){

        $data= CouponModel::select($fields)->get();
        return ob_to_array($data);
    }

    public   function getCategory(string $name){
        $cha_id= ChannelModel::where("cha_name",$name)->value('cha_id');
        if(empty($cha_id))  return error('参数错误');
        $data= CategoryModel::where('cha_id',$cha_id)->select("cate_id","cate_name","pid")->get();
        $data=ob_to_array($data);
        if(empty($data)){
            return error('无分类');
        }

        $pid_ar=array_unique(array_column($data,'pid'));
        foreach($data as $k=>$v){
            if(in_array($v['cate_id'],$pid_ar)){
                $data[$k]['is_son']=0;
            }else{
                $data[$k]['is_son']=1;
            }
        }

        $data=$this->tree($data);
        $html="<option value='0'>不选</option><option value='all'>全部</option>";
        foreach($data as $k=>$v){
            if($v['is_son']==0){
                $html.='<option value="'.$v['cate_id'].'"    >'.$v['level_str'].$v['cate_name'].'</option>';
            }else{
                $html.='<option value="'.$v['cate_id'].'"   >'.$v['level_str'].$v['cate_name'].'</option>';
            }
        }
        return success('ok',['html'=>$html]);
    }

    //获取一个
    public static function  getOne($cou_id,$fields=['*']){
        $cou_id=(int)$cou_id;
        $data= CouponModel::where('brand_id',$cou_id)->select($fields)->first();
        return ob_to_array($data);
    }


    //判断该数据是否存在
    public static function isOne($cou_id){
        $cou_id=(int)$cou_id;

        return CouponModel::where('brand_id',$cou_id)->count();
    }





}
